from django.shortcuts import render
from django.views.generic import CreateView
from django_redis import get_redis_connection

from rest_framework import status
from rest_framework.permissions import IsAuthenticated
from rest_framework.generics import GenericAPIView, RetrieveAPIView,CreateAPIView,UpdateAPIView
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.serializers import Serializer
from rest_framework import mixins
from rest_framework.viewsets import GenericViewSet
from rest_framework.decorators import action
from rest_framework_jwt.views import ObtainJSONWebToken

from goods.models import SKU
from goods.serializers import SKUSerializer
from .serializers import AddUserBrowsingHistorySerializer
from .models import User
from . import serializers
from . import constants
from carts.utils import merge_cart_cookie_to_redis
# Create your views here.


class UserAuthorizeView(ObtainJSONWebToken):
    """
    自定义、重写账号登录系统
    目的：在保留账号登录原有的逻辑不变的前提下，只需要追加合并购物车的业务逻辑即可
    """
    def post(self, request, *args, **kwargs):
        # 保留账号登录原有的逻辑不变
        response = super(UserAuthorizeView, self).post(request, *args, **kwargs)

        # 获取验证之后的user对象
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid(raise_exception=True):
            user = serializer.object.get('user') or request.user

            # 合并购物车
            response = merge_cart_cookie_to_redis(request=request, user=user, response=response)

        return response



class UserDetailView(RetrieveAPIView):
    """
    用户基本信息
    1、必须用户登录后才能访问该接口
    2、因为目前前端没有传入主键到视图中，所以RetrieveAPIView中的get—object（）方法无法获取到pk，所以重写
    """
    # 指定权限：必须用户登录后才能访问该接口
    permission_classes = [IsAuthenticated]

    # 指定序列化器
    serializer_class = serializers.UserDetailSerializer

    def get_object(self):
        """在这个方法中返回当前的登录用户的user的信息"""
        return self.request.user


class VerifyEmailView(APIView):
    """
    验证邮箱
    目的：获取token，读取user——id，查询出当前要认证的用户，将用户的email-active设置True
    """
    def get(self,request):
        # 获取token
        token = request.query_params.get('token')
        if token is None:
            return Response({"message":"缺少token"},status=status.HTTP_400_BAD_REQUEST)
        # 读取出user-id，查询当前要认证的用户
        user = User.check_verify_email_token(token)
        if user is None:
            return Response({"message":"无效token"},status=status.HTTP_400_BAD_REQUEST)
        # 将用户的email-active设置True
        user.email_active = True
        user.save()

        # 响应结果
        return Response({"message":"OK"})


class EmailView(UpdateAPIView):
    """添加邮箱"""

    # 指定权限：必须用户登录后才能访问接口
    permission_classes = [IsAuthenticated]

    # 指定序列化器
    serializer_class = serializers.EmailSerializer

    def get_object(self):
        """在这个方法中返回当前的用户登录的user信息"""
        return self.request.user


class UserView(CreateAPIView):
    """
    注册
    新增（用户数据-->校验-->反序列化-->create（）-- > save（） ； 保存影虎传入的数据到数据库
    """
    # 指定序列化器
    serializer_class = serializers.CreateUserSerializer


# url(r'^usernames/(?P<username>\w{5,20})/count/$', views.UsernameCountView.as_view()),
class UsernameCountView(APIView):
    """用户名数量  判断用户是否存在"""
    def get(self,request,username):
        """获取指定用户名数量"""
        count = User.objects.filter(username=username).count()
        data = {
            'username':username,
            'count':count
        }

        return Response(data)

# 检查手机号是否存在
class MobileCountView(APIView):
    """手机号数量"""
    def get(self,request,mobile):
        """获取指定手机号"""
        count = User.objects.filter(mobile=mobile).count()

        data = {
            'mobile':mobile,
            'count':count
        }

        return Response(data)


class AddressViewSet(mixins.CreateModelMixin,mixins.UpdateModelMixin,GenericViewSet):
    """
    用户地址新增域修改
    """
    serializer_class = serializers.UserAddressSerializer
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        return self.request.user.addresses.filter(is_deleted=False)

    # GET /addresses/
    def list(self,request,*args,**kwargs):
        """
        用户地址列表
        :return:
        """
        queryset = self.get_queryset()
        """get_serializer 会给序列化器添加三个属性
            request: 当前视图的请求对象
            view：当前请求的类视图对象
            format：当前请求期望返回的数据格式
        """
        serializer = self.get_serializer(queryset,many=True)
        user = self.request.user
        return Response({
            'user_id':user.id,
            'default_address_id':user.default_address_id,
            'limit':constants.USER_ADDRESS_COUNTS_LIMIT,
            'addresses':serializer.data,
        })

    # POST /addresses/
    def create(self,request,*args,**kwargs):
        """
        保存用户地址数据
        :return:
        """
        #  检查用户地址数据数目不能超过上限
        count = request.user.addresses.count()
        if count >= constants.USER_ADDRESS_COUNTS_LIMIT:
            return Response({'message':"保存地址数据已达上限"},status=status.HTTP_400_BAD_REQUEST)
        return super(AddressViewSet, self).create(request,*args,**kwargs)

    # delete /addresses/<pk>/
    def destroy(self,request,*args,**kwargs):
        """
        处理删除
        :param request:当前视图的请求对象
        :param args:
        :param kwargs:
        :return:
        """
        address = self.get_object()

        # 逻辑删除
        address.is_deleted = True
        address.save()

        return Response(status=status.HTTP_204_NO_CONTENT)

    # put /addresses/pk/status/
    @action(methods=['put'],detail=True)
    def status(self,request,pk=None):
        """
        设置默认地址
        :param request:
        :param pk:
        :return:
        """
        address = self.get_object()
        request.user.default_address = address
        request.user.save()
        return Response(status=status.HTTP_201_CREATED)

    # put /addresses/pk/title/
        #  需要请求体参数 title
    @action(methods=['put'],detail=True)
    def title(self,request,pk=None):
        """
        修改标题
        """
        address = self.get_object()
        serializer = serializers.AddressTitleSerializer(instance=address,data=request.data)
        serializer.save()
        return Response(serializer.data)


class UserBrowsingHistoryView(CreateAPIView):
    """
    用户浏览历史记录
    """
    serializer_class = AddUserBrowsingHistorySerializer
    permission_classes = [IsAuthenticated]

    def get(self, request):
        """
        获取
        """
        user_id = request.user.id

        redis_conn = get_redis_connection("history")
        history = redis_conn.lrange("history_%s" % user_id, 0, constants.USER_BROWSING_HISTORY_COUNTS_LIMIT - 1)
        skus = []
        # 为了保持查询出的顺序与用户的浏览历史保存顺序一致
        for sku_id in history:
            sku = SKU.objects.get(id=sku_id)
            skus.append(sku)

        s = SKUSerializer(skus, many=True)
        return Response(s.data)









